// 安全的游戏增强系统 - 绝不破坏原游戏
(function() {
    'use strict';
    
    console.log('🛡️ 安全增强系统启动...');
    
    class SafeEnhancements {
        constructor() {
            this.enabled = false;
            this.dodgeCooldown = 0;
            this.comboCount = 0;
            this.lastKillTime = 0;
            this.environmentObjects = [];
            this.lastZombieCount = 0;
            this.gameReady = false;
            
            // 安全初始化
            this.safeInitialize();
        }
        
        safeInitialize() {
            console.log('🔒 开始安全初始化...');
            
            // 立即设置不依赖游戏引擎的功能
            this.setupSafeFeatures();
            
            // 延迟检查游戏状态
            this.waitForGameSafely();
        }
        
        setupSafeFeatures() {
            // 1. 安全的闪避系统 (不依赖游戏引擎)
            this.setupSafeDodge();
            
            // 2. 创建状态显示
            this.createSafeStatusDisplay();
            
            this.enabled = true;
            console.log('✅ 基础功能已安全启用');
        }
        
        waitForGameSafely() {
            let attempts = 0;
            const maxAttempts = 30;
            
            const checkGame = () => {
                attempts++;
                
                try {
                    if (window.gameEngine && 
                        window.player && 
                        window.levelManager && 
                        window.gameEngine.gameState) {
                        
                        console.log('✅ 游戏系统安全检测完成');
                        this.gameReady = true;
                        this.setupGameFeatures();
                        return;
                    }
                } catch (error) {
                    console.log('⚠️ 游戏系统检测中...');
                }
                
                if (attempts < maxAttempts) {
                    setTimeout(checkGame, 1000);
                } else {
                    console.log('⚠️ 游戏集成跳过，基础功能仍可用');
                }
            };
            
            setTimeout(checkGame, 3000); // 给游戏更多时间加载
        }
        
        setupSafeDodge() {
            console.log('🏃 设置安全闪避...');
            
            document.addEventListener('keydown', (e) => {
                if (e.code === 'Space' && this.dodgeCooldown <= 0) {
                    e.preventDefault();
                    this.performSafeDodge();
                }
            });
            
            // 冷却更新
            setInterval(() => {
                if (this.dodgeCooldown > 0) {
                    this.dodgeCooldown -= 50;
                }
            }, 50);
        }
        
        performSafeDodge() {
            console.log('🏃 安全闪避执行');
            this.dodgeCooldown = 1000;
            
            // 安全的视觉效果
            this.showSafeDodgeEffect();
            
            // 安全的无敌效果
            try {
                if (window.player) {
                    window.player.invulnerable = true;
                    setTimeout(() => {
                        if (window.player) {
                            window.player.invulnerable = false;
                        }
                    }, 300);
                }
            } catch (error) {
                // 静默处理错误
            }
        }
        
        showSafeDodgeEffect() {
            // 创建安全的闪烁效果
            const flash = document.createElement('div');
            flash.style.cssText = `
                position: fixed; top: 0; left: 0; width: 100%; height: 100%;
                background: rgba(255, 255, 255, 0.2); pointer-events: none;
                z-index: 5000; opacity: 0.5;
            `;
            
            document.body.appendChild(flash);
            
            // 淡出效果
            let opacity = 0.5;
            const fadeOut = setInterval(() => {
                opacity -= 0.05;
                flash.style.opacity = opacity;
                if (opacity <= 0) {
                    clearInterval(fadeOut);
                    if (flash.parentNode) {
                        document.body.removeChild(flash);
                    }
                }
            }, 20);
            
            // 安全的粒子效果
            this.createSafeParticles();
        }
        
        createSafeParticles() {
            try {
                if (window.gameEngine && window.gameEngine.particles && window.player) {
                    for (let i = 0; i < 6; i++) {
                        window.gameEngine.particles.push({
                            x: window.player.x + (Math.random() - 0.5) * 20,
                            y: window.player.y + (Math.random() - 0.5) * 20,
                            vx: (Math.random() - 0.5) * 100,
                            vy: (Math.random() - 0.5) * 100,
                            life: 0.4,
                            maxLife: 0.4,
                            color: '#FFFFFF',
                            size: Math.random() * 4 + 1
                        });
                    }
                }
            } catch (error) {
                // 静默处理，不影响游戏
            }
        }
        
        createSafeStatusDisplay() {
            const statusDiv = document.createElement('div');
            statusDiv.id = 'safeStatus';
            statusDiv.style.cssText = `
                position: fixed; top: 10px; right: 10px; z-index: 9999;
                background: linear-gradient(135deg, rgba(0,0,0,0.8), rgba(30,30,30,0.8));
                color: white; padding: 12px; border-radius: 8px; 
                font-family: 'Courier New', monospace; font-size: 11px;
                border: 2px solid #4ECDC4; min-width: 160px;
                box-shadow: 0 4px 8px rgba(0,0,0,0.3);
            `;
            statusDiv.innerHTML = `
                <div style="color: #4ECDC4; font-weight: bold; margin-bottom: 6px; text-align: center;">🎮 增强状态</div>
                <div id="safeDodgeStatus" style="margin: 3px 0;">🏃 闪避: 准备就绪</div>
                <div id="safeComboStatus" style="margin: 3px 0;">🔥 连击: 0x</div>
                <div id="safeGameStatus" style="margin: 3px 0;">🎯 状态: 等待中</div>
                <div style="color: #888; font-size: 9px; margin-top: 6px; text-align: center;">空格-闪避</div>
            `;
            
            document.body.appendChild(statusDiv);
            
            // 定期更新
            setInterval(() => {
                this.updateSafeStatus();
            }, 100);
        }
        
        updateSafeStatus() {
            const dodgeStatus = document.getElementById('safeDodgeStatus');
            const comboStatus = document.getElementById('safeComboStatus');
            const gameStatus = document.getElementById('safeGameStatus');
            
            if (dodgeStatus) {
                if (this.dodgeCooldown > 0) {
                    dodgeStatus.innerHTML = `🏃 闪避: ${(this.dodgeCooldown / 1000).toFixed(1)}s`;
                    dodgeStatus.style.color = '#FF6B6B';
                } else {
                    dodgeStatus.innerHTML = '🏃 闪避: 准备就绪';
                    dodgeStatus.style.color = '#4ECDC4';
                }
            }
            
            if (comboStatus) {
                let color = '#FFFFFF';
                if (this.comboCount >= 10) color = '#FFD700';
                else if (this.comboCount >= 5) color = '#00FF00';
                
                comboStatus.innerHTML = `🔥 连击: ${this.comboCount}x`;
                comboStatus.style.color = color;
            }
            
            if (gameStatus) {
                if (this.gameReady) {
                    gameStatus.innerHTML = '🎯 状态: 已连接';
                    gameStatus.style.color = '#00FF00';
                } else {
                    gameStatus.innerHTML = '🎯 状态: 等待中';
                    gameStatus.style.color = '#FFD700';
                }
            }
            
            // 连击超时检查
            const now = Date.now();
            if (this.comboCount > 0 && now - this.lastKillTime > 3000) {
                this.comboCount = 0;
            }
        }
        
        setupGameFeatures() {
            console.log('🎮 设置游戏功能...');
            
            try {
                // 安全的击杀监控
                this.setupSafeKillTracking();
                
                // 安全的环境系统
                this.setupSafeEnvironment();
                
                // 安全的渲染集成
                this.setupSafeRendering();
                
                console.log('✅ 游戏功能安全启用');
                
            } catch (error) {
                console.error('⚠️ 游戏功能启用失败，基础功能仍可用:', error);
            }
        }
        
        setupSafeKillTracking() {
            setInterval(() => {
                try {
                    if (window.gameEngine && window.gameEngine.zombies) {
                        const currentCount = window.gameEngine.zombies.length;
                        
                        if (this.lastZombieCount > 0 && currentCount < this.lastZombieCount) {
                            const kills = this.lastZombieCount - currentCount;
                            for (let i = 0; i < kills; i++) {
                                this.addSafeKill();
                            }
                        }
                        
                        this.lastZombieCount = currentCount;
                    }
                } catch (error) {
                    // 静默处理
                }
            }, 200);
        }
        
        addSafeKill() {
            const now = Date.now();
            
            if (now - this.lastKillTime > 3000) {
                this.comboCount = 1;
            } else {
                this.comboCount++;
            }
            
            this.lastKillTime = now;
            
            console.log(`🔥 安全连击: ${this.comboCount}x`);
            
            // 显示连击效果
            this.showSafeComboEffect();
            
            // 连击奖励
            if (this.comboCount % 5 === 0) {
                this.giveSafeComboReward();
            }
        }
        
        showSafeComboEffect() {
            // 安全的连击显示
            const comboDiv = document.createElement('div');
            comboDiv.style.cssText = `
                position: fixed; top: 40%; left: 50%; transform: translate(-50%, -50%);
                font-size: 32px; font-weight: bold; color: #FFD700;
                text-shadow: 2px 2px 4px rgba(0,0,0,0.8); z-index: 8000;
                pointer-events: none; font-family: monospace;
            `;
            comboDiv.textContent = `${this.comboCount}x`;
            
            document.body.appendChild(comboDiv);
            
            // 动画效果
            let scale = 0.5;
            let opacity = 1;
            const animate = setInterval(() => {
                scale += 0.02;
                opacity -= 0.02;
                
                comboDiv.style.transform = `translate(-50%, -50%) scale(${scale})`;
                comboDiv.style.opacity = opacity;
                
                if (opacity <= 0) {
                    clearInterval(animate);
                    if (comboDiv.parentNode) {
                        document.body.removeChild(comboDiv);
                    }
                }
            }, 20);
        }
        
        giveSafeComboReward() {
            try {
                if (window.player && window.player.health < window.player.maxHealth) {
                    window.player.health = Math.min(window.player.maxHealth, window.player.health + 10);
                    if (window.player.updateHealthUI) {
                        window.player.updateHealthUI();
                    }
                    
                    // 显示奖励
                    this.showSafeReward('+10 生命值');
                }
            } catch (error) {
                console.log('⚠️ 奖励应用失败');
            }
        }
        
        showSafeReward(text) {
            const reward = document.createElement('div');
            reward.style.cssText = `
                position: fixed; top: 25%; left: 50%; transform: translateX(-50%);
                font-size: 20px; color: #00FF00; font-weight: bold;
                text-shadow: 2px 2px 4px rgba(0,0,0,0.8); z-index: 8000;
                pointer-events: none; font-family: monospace;
            `;
            reward.textContent = text;
            
            document.body.appendChild(reward);
            
            // 上升淡出动画
            let y = 25;
            let opacity = 1;
            const animate = setInterval(() => {
                y -= 0.5;
                opacity -= 0.02;
                
                reward.style.top = y + '%';
                reward.style.opacity = opacity;
                
                if (opacity <= 0) {
                    clearInterval(animate);
                    if (reward.parentNode) {
                        document.body.removeChild(reward);
                    }
                }
            }, 20);
        }
        
        setupSafeEnvironment() {
            console.log('🌍 创建安全环境...');
            
            // 等待关卡真正开始
            const waitForLevel = setInterval(() => {
                try {
                    if (window.gameEngine && 
                        window.gameEngine.gameState === 'playing' && 
                        window.levelManager && 
                        window.levelManager.currentLevel > 0) {
                        
                        this.createRealisticEnvironment();
                        clearInterval(waitForLevel);
                    }
                } catch (error) {
                    // 继续等待
                }
            }, 1000);
        }
        
        createRealisticEnvironment() {
            console.log('🏗️ 创建真实环境物品...');
            
            this.environmentObjects = [];
            
            // 创建真实的桌子 (更大，更明显)
            for (let i = 0; i < 4; i++) {
                this.environmentObjects.push({
                    x: Math.random() * 600 + 200,
                    y: Math.random() * 400 + 200,
                    width: 60,
                    height: 40,
                    health: 3,
                    maxHealth: 3,
                    type: 'realistic_table',
                    destroyed: false
                });
            }
            
            // 创建真实的爆炸桶
            for (let i = 0; i < 2; i++) {
                this.environmentObjects.push({
                    x: Math.random() * 500 + 250,
                    y: Math.random() * 300 + 250,
                    width: 35,
                    height: 45,
                    health: 1,
                    type: 'realistic_barrel',
                    destroyed: false
                });
            }
            
            console.log(`✅ 创建了 ${this.environmentObjects.length} 个真实环境物品`);
            
            // 安全的碰撞检测
            this.startSafeCollisionDetection();
        }
        
        startSafeCollisionDetection() {
            setInterval(() => {
                try {
                    if (window.gameEngine && 
                        window.gameEngine.bullets && 
                        window.gameEngine.gameState === 'playing') {
                        
                        this.checkSafeCollisions();
                    }
                } catch (error) {
                    // 静默处理
                }
            }, 50);
        }
        
        checkSafeCollisions() {
            window.gameEngine.bullets.forEach((bullet, bulletIndex) => {
                this.environmentObjects.forEach(obj => {
                    if (!obj.destroyed && this.isColliding(bullet, obj)) {
                        // 安全移除子弹
                        try {
                            window.gameEngine.bullets.splice(bulletIndex, 1);
                        } catch (error) {
                            // 移除失败也没关系
                        }
                        
                        // 伤害物品
                        obj.health--;
                        console.log(`💥 击中 ${obj.type}, 剩余血量: ${obj.health}`);
                        
                        if (obj.health <= 0) {
                            obj.destroyed = true;
                            
                            if (obj.type === 'realistic_barrel') {
                                this.safeExplodeBarrel(obj);
                            } else {
                                this.safeCreateDebris(obj);
                            }
                        }
                    }
                });
            });
        }
        
        safeExplodeBarrel(barrel) {
            console.log('💥 真实爆炸桶爆炸！');
            
            // 安全的爆炸效果
            this.showSafeExplosion();
            
            // 安全的粒子效果
            try {
                if (window.gameEngine && window.gameEngine.particles) {
                    for (let i = 0; i < 15; i++) {
                        const angle = (Math.PI * 2 * i) / 15;
                        const speed = Math.random() * 150 + 80;
                        
                        window.gameEngine.particles.push({
                            x: barrel.x + barrel.width/2,
                            y: barrel.y + barrel.height/2,
                            vx: Math.cos(angle) * speed,
                            vy: Math.sin(angle) * speed,
                            life: Math.random() * 1.5 + 0.5,
                            maxLife: Math.random() * 1.5 + 0.5,
                            color: ['#FF4500', '#FF6347', '#FFD700', '#DC143C'][Math.floor(Math.random() * 4)],
                            size: Math.random() * 8 + 3
                        });
                    }
                }
            } catch (error) {
                // 粒子失败也没关系
            }
            
            // 安全的伤害检测
            this.safeDamageZombies(barrel);
        }
        
        showSafeExplosion() {
            const explosion = document.createElement('div');
            explosion.style.cssText = `
                position: fixed; top: 0; left: 0; width: 100%; height: 100%;
                background: radial-gradient(circle, rgba(255,100,0,0.6) 0%, transparent 70%);
                pointer-events: none; z-index: 6000;
            `;
            
            document.body.appendChild(explosion);
            
            let opacity = 0.6;
            const fade = setInterval(() => {
                opacity -= 0.03;
                explosion.style.opacity = opacity;
                
                if (opacity <= 0) {
                    clearInterval(fade);
                    if (explosion.parentNode) {
                        document.body.removeChild(explosion);
                    }
                }
            }, 20);
        }
        
        safeDamageZombies(barrel) {
            try {
                if (window.gameEngine && window.gameEngine.zombies) {
                    const explosionRadius = 80;
                    
                    window.gameEngine.zombies.forEach(zombie => {
                        const distance = this.getDistance(zombie, {
                            x: barrel.x + barrel.width/2,
                            y: barrel.y + barrel.height/2
                        });
                        
                        if (distance < explosionRadius) {
                            const damage = Math.floor(40 * (1 - distance / explosionRadius));
                            zombie.health -= damage;
                            
                            if (zombie.health <= 0) {
                                // 这会被击杀监控捕获
                            }
                        }
                    });
                }
            } catch (error) {
                // 伤害失败也没关系
            }
        }
        
        safeCreateDebris(obj) {
            try {
                if (window.gameEngine && window.gameEngine.particles) {
                    for (let i = 0; i < 8; i++) {
                        window.gameEngine.particles.push({
                            x: obj.x + Math.random() * obj.width,
                            y: obj.y + Math.random() * obj.height,
                            vx: (Math.random() - 0.5) * 120,
                            vy: (Math.random() - 0.5) * 120,
                            life: Math.random() * 1.2 + 0.8,
                            maxLife: Math.random() * 1.2 + 0.8,
                            color: ['#8B4513', '#654321', '#A0522D'][Math.floor(Math.random() * 3)],
                            size: Math.random() * 5 + 2
                        });
                    }
                }
            } catch (error) {
                // 碎片失败也没关系
            }
        }
        
        setupSafeRendering() {
            console.log('🎨 设置安全渲染...');
            
            // 不修改原游戏的渲染函数，而是使用独立的渲染循环
            setInterval(() => {
                this.safeRender();
            }, 16);
        }
        
        safeRender() {
            try {
                if (window.gameEngine && 
                    window.gameEngine.ctx && 
                    window.gameEngine.gameState === 'playing' &&
                    this.gameReady) {
                    
                    this.renderRealisticEnvironment(window.gameEngine.ctx);
                    this.renderGameUI(window.gameEngine.ctx);
                }
            } catch (error) {
                // 渲染失败也没关系
            }
        }
        
        renderRealisticEnvironment(ctx) {
            ctx.save();
            
            this.environmentObjects.forEach(obj => {
                if (obj.destroyed) return;
                
                if (obj.type === 'realistic_table') {
                    this.drawRealisticTable(ctx, obj);
                } else if (obj.type === 'realistic_barrel') {
                    this.drawRealisticBarrel(ctx, obj);
                }
            });
            
            ctx.restore();
        }
        
        drawRealisticTable(ctx, table) {
            // 绘制真实的桌子
            ctx.save();
            
            // 桌面
            const gradient = ctx.createLinearGradient(table.x, table.y, table.x + table.width, table.y + table.height);
            gradient.addColorStop(0, '#D2691E');
            gradient.addColorStop(0.5, '#8B4513');
            gradient.addColorStop(1, '#654321');
            
            ctx.fillStyle = gradient;
            ctx.fillRect(table.x, table.y, table.width, table.height);
            
            // 桌面边框
            ctx.strokeStyle = '#654321';
            ctx.lineWidth = 2;
            ctx.strokeRect(table.x, table.y, table.width, table.height);
            
            // 桌腿
            const legWidth = 4;
            const legHeight = 8;
            ctx.fillStyle = '#654321';
            
            // 四个桌腿
            ctx.fillRect(table.x + 2, table.y + table.height, legWidth, legHeight);
            ctx.fillRect(table.x + table.width - legWidth - 2, table.y + table.height, legWidth, legHeight);
            ctx.fillRect(table.x + 2, table.y + table.height - 4, legWidth, legHeight);
            ctx.fillRect(table.x + table.width - legWidth - 2, table.y + table.height - 4, legWidth, legHeight);
            
            // 损坏效果
            if (table.health < table.maxHealth) {
                ctx.fillStyle = 'rgba(139, 69, 19, 0.7)';
                ctx.fillRect(table.x + 5, table.y + 5, table.width - 10, table.height - 10);
                
                // 裂痕
                ctx.strokeStyle = '#2F1B14';
                ctx.lineWidth = 1;
                ctx.beginPath();
                ctx.moveTo(table.x + table.width * 0.2, table.y + table.height * 0.2);
                ctx.lineTo(table.x + table.width * 0.8, table.y + table.height * 0.7);
                ctx.stroke();
            }
            
            ctx.restore();
        }
        
        drawRealisticBarrel(ctx, barrel) {
            // 绘制真实的爆炸桶
            ctx.save();
            
            // 桶身渐变
            const gradient = ctx.createLinearGradient(barrel.x, barrel.y, barrel.x + barrel.width, barrel.y + barrel.height);
            gradient.addColorStop(0, '#DC143C');
            gradient.addColorStop(0.3, '#B22222');
            gradient.addColorStop(0.7, '#8B0000');
            gradient.addColorStop(1, '#660000');
            
            ctx.fillStyle = gradient;
            ctx.fillRect(barrel.x, barrel.y, barrel.width, barrel.height);
            
            // 金属环
            ctx.strokeStyle = '#696969';
            ctx.lineWidth = 2;
            for (let i = 0; i < 3; i++) {
                const y = barrel.y + (barrel.height / 4) * (i + 1);
                ctx.beginPath();
                ctx.moveTo(barrel.x, y);
                ctx.lineTo(barrel.x + barrel.width, y);
                ctx.stroke();
            }
            
            // 危险标志
            ctx.fillStyle = '#FFD700';
            ctx.font = 'bold 12px monospace';
            ctx.textAlign = 'center';
            ctx.fillText('⚠', barrel.x + barrel.width/2, barrel.y + barrel.height/2 + 4);
            
            // 反光效果
            const highlight = ctx.createLinearGradient(barrel.x, barrel.y, barrel.x + barrel.width/3, barrel.y);
            highlight.addColorStop(0, 'rgba(255, 255, 255, 0.3)');
            highlight.addColorStop(1, 'rgba(255, 255, 255, 0)');
            
            ctx.fillStyle = highlight;
            ctx.fillRect(barrel.x, barrel.y, barrel.width/3, barrel.height);
            
            // 边框
            ctx.strokeStyle = '#2F1B14';
            ctx.lineWidth = 1;
            ctx.strokeRect(barrel.x, barrel.y, barrel.width, barrel.height);
            
            ctx.restore();
        }
        
        renderGameUI(ctx) {
            if (this.comboCount > 0) {
                ctx.save();
                ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
                ctx.fillRect(450, 60, 100, 30);
                
                ctx.fillStyle = '#FFD700';
                ctx.font = 'bold 16px monospace';
                ctx.textAlign = 'center';
                ctx.fillText(`${this.comboCount}x 连击`, 500, 80);
                ctx.restore();
            }
        }
        
        // 工具函数
        isColliding(obj1, obj2) {
            const o1 = {
                x: obj1.x - (obj1.radius || 3),
                y: obj1.y - (obj1.radius || 3),
                width: (obj1.radius || 3) * 2,
                height: (obj1.radius || 3) * 2
            };
            
            return o1.x < obj2.x + obj2.width &&
                   o1.x + o1.width > obj2.x &&
                   o1.y < obj2.y + obj2.height &&
                   o1.y + o1.height > obj2.y;
        }
        
        getDistance(obj1, obj2) {
            const dx = obj1.x - obj2.x;
            const dy = obj1.y - obj2.y;
            return Math.sqrt(dx * dx + dy * dy);
        }
    }
    
    // 安全创建实例
    try {
        window.safeEnhancements = new SafeEnhancements();
        console.log('✅ 安全增强系统已加载');
    } catch (error) {
        console.error('❌ 安全增强系统加载失败:', error);
    }
    
})();